/*
 * Copyright (C) 2011 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.ztewatch.wearcontacts.loader;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.content.CursorLoader;
import android.database.Cursor;
import android.database.MatrixCursor;
import android.database.MergeCursor;
import android.os.Bundle;
import android.provider.ContactsContract.CommonDataKinds.GroupMembership;
import android.provider.ContactsContract.Contacts;
import android.provider.ContactsContract.Data;
import android.provider.ContactsContract.RawContacts;

import com.ztewatch.wearcontacts.R;
import com.ztewatch.wearcontacts.utils.ContactQuery;

/**
 * A loader for use in the default contact list, which will also query for the
 * user's group if configured to do so.
 */
public class GroupSelectContactLoader extends CursorLoader {
	private Context mContext;

	public GroupSelectContactLoader(Context context) {
		super(context);
		mContext = context;
	}

	public void setLoadProfile(boolean flag) {
	}

	public void setProjection(String[] projection) {
		super.setProjection(projection);
	}

	@Override
	public Cursor loadInBackground() {
		List<Cursor> cursors = new ArrayList<Cursor>();
		Cursor cursor = null;
		try {
			cursor = super.loadInBackground();
		} catch (NullPointerException e) {
		}

		// add history start
		MatrixCursor matrix = new MatrixCursor(ContactQuery.CONTACT_PROJECTION);
//		Object[] addHistory = new Object[ContactQuery.CONTACT_PROJECTION.length];
//		for (int i = 0; i < addHistory.length; i++) {
//			if (Contacts.DISPLAY_NAME_PRIMARY
//					.equals(ContactQuery.CONTACT_PROJECTION[i])) {
//				addHistory[i] = mContext.getString(R.string.history_str);
//			}
//		}
//		matrix.addRow(addHistory);
		// add history end
		Object[] row = new Object[ContactQuery.CONTACT_PROJECTION.length];
		while (cursor != null && cursor.moveToNext()) {
			for (int i = 0; i < row.length; i++) {
				row[i] = cursor.getString(i);
			}
			matrix.addRow(row);
		}

		final Cursor contactsCursor = cursor;
		cursors.add(matrix);
		cursors.add(loadNoGroupContact());
		return new MergeCursor(cursors.toArray(new Cursor[cursors.size()])) {
			@Override
			public Bundle getExtras() {
				return contactsCursor == null ? new Bundle() : contactsCursor
						.getExtras();
			}
		};
	}

	private Cursor loadNoGroupContact() {
		StringBuilder selection = new StringBuilder();
		List<String> selectionArgs = new ArrayList<String>();
		String DATA_JOIN_MIMETYPES = "data JOIN mimetypes ON (data.mimetype_id = mimetypes._id)";
		selection.append(Contacts._ID + " IN " + "(SELECT "
				+ RawContacts.CONTACT_ID + " FROM  RAW_CONTACTS " + " WHERE "
				+ RawContacts.DELETED + " = 0 AND RAW_CONTACTS._ID NOT IN "
				+ "(SELECT DATA.RAW_CONTACT_ID" + " FROM "
				+ DATA_JOIN_MIMETYPES + " WHERE " + Data.MIMETYPE + "='"
				+ GroupMembership.CONTENT_ITEM_TYPE + "'" + "))");

		Cursor cursor = getContext().getContentResolver().query(
				Contacts.CONTENT_URI, ContactQuery.CONTACT_PROJECTION,
				selection.toString(), selectionArgs.toArray(new String[0]),
				null);
		return cursor;
	}

}
